package cn.tedu.seckill.controller

import java.util.List

import org.apache.commons.lang.math.RandomUtils
import org.springframework.amqp.rabbit.core.RabbitTemplate
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

import cn.tedu.common.pojo.Seckill
import cn.tedu.common.pojo.Success
import cn.tedu.common.pojo.SysResult
import cn.tedu.seckill.mapper.SucMapper
import cn.tedu.seckill.service.SecService

/**
 * seckill表格数据相关的入口controller
 *
 * @author Administrator
 */
@RestController
class SecController {
  @Autowired
  private val secService: SecService = null

  // 查询所有可以秒杀的商品数据
  @RequestMapping(Array("seckill/manage/list"))
  def queryAll = secService queryAll

  // 根据秒杀商品id查询详情信息
  @RequestMapping(Array("seckill/manage/detail"))
  def queryOne(seckillId: Long) = secService queryOne seckillId

  // 接收秒杀商品的请求
  @Autowired
  private val client: RabbitTemplate = null

  @RequestMapping(Array("seckill/manage/{seckillId}"))
  def startSeckill(@PathVariable seckillId: Long) = {
    // 确定用户身份,userId,username userPhone
    // 前端没有实现js限制未登录的秒杀,
    // 随机生成一个手机号
    val userPhone = "133888" + RandomUtils.nextInt(999)
    // 发送消息 确定用户身份,秒杀商品消息
    // 一个用户最多可以秒杀3个商品?怎么做?list hash set
    // list的llen hash hlen set 的scart userId/userPhone作为key的核心
    // seckillId做value中数据 redis的锁 pipeLine
    val msg = userPhone + "/" + seckillId
    try {
      client.convertAndSend("seckillEX", "seckill", msg); SysResult ok
    } catch {
      case e: Exception => e.printStackTrace(); SysResult ok
    }
  }

  // 展示成功者
  @Autowired
  private val sucMapper: SucMapper = null

  @RequestMapping(Array("seckill/manage/{seckillId}/userPhone"))
  def querySuccess(@PathVariable seckillId: Long) = sucMapper queryAllSuccess seckillId
}